package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dao.AddressBookDao;
import com.itheima.reggie.domain.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookDao, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookDao addressBookDao;

    @Override
    public AddressBook setById(AddressBook addressBook) {

        UpdateWrapper<AddressBook> uw = new UpdateWrapper<>();
        uw.eq("user_id", BaseContext.getThreadLocal());
        uw.set("is_default", 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        update(uw);
        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookDao.updateById(addressBook);


        return addressBook;
    }

    @Override
    public AddressBook findOne() {

        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getThreadLocal());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        AddressBook addressBook = addressBookDao.selectOne(queryWrapper);

        return addressBook;
    }

    @Override
    public List<AddressBook> findAddressBookList(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getThreadLocal());
        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);

        //select * from address_book where user_id=? order by update_time desc
        List<AddressBook> addressBooks = addressBookDao.selectList(queryWrapper);
        return addressBooks;
    }
}